<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\common\library\eOrder\provider\driver;

use app\common\library\helper;
use app\common\library\eOrder\provider\Driver;
use cores\exception\BaseException;

/**
 * 快递鸟驱动
 * Class Kdniao
 * @package app\common\library\eOrder\provider\driver
 */
class Kdniao extends Driver
{
    // API地址
    const API_URL = 'https://api.kdniao.com/api/EOrderService';

    /**
     * 获取电子面单内容 (HTML格式)
     * @return array
     * @throws BaseException
     */
    public function handle(): array
    {
        $result = $this->getElecOrder();
        return [
            // 快递单号
            'expressNo' => $result['Order']['LogisticCode'],
            // 电子面单模板内容 (html)
            'content' => $result['PrintTemplate'],
        ];
    }

    /**
     * API：获取电子面单内容
     * @return array|mixed
     * @throws BaseException
     */
    public function getElecOrder()
    {
        // 组装应用级参数
        $requestData = helper::jsonEncode([
            // 订单编号, 不可重复提交
            'OrderCode' => $this->deliverOrder['orderCode'],
            // 快递公司编码 详细编码参考《快递鸟接口支持快递公司编码.xlsx》
            'ShipperCode' => $this->eleTemplate['shipperCode'],
            // 电子面单客户号
            'CustomerName' => $this->eleTemplate['customerName'],
            // 电子面单密码
            'CustomerPwd' => $this->eleTemplate['customerPwd'],
            // 网点编码
            'SendSite' => $this->eleTemplate['sendSite'],
            // 邮费支付方式: 1-现付，2-到付，3-月结，4-第三方支付(仅SF支持)
            'PayType' => $this->payType($this->eleTemplate['payType']),
            // 月结号(选填)
            'MonthCode' => $this->eleTemplate['monthCode'],
            // 快递类型：1-标准快件 ,详细快递类型参考《快递公司快递业务类型.xlsx》
            'ExpType' => 1,
            // 发件人信息
            'Sender' => [
                'Name' => $this->sender['name'],
                'Mobile' => $this->sender['mobile'],
                'ProvinceName' => $this->sender['provinceName'],
                'CityName' => $this->sender['cityName'],
                'ExpAreaName' => $this->sender['expAreaName'],
                'Address' => $this->sender['address'],
            ],
            // 收件人信息
            'Receiver' => [
                'Name' => $this->receiver['name'],
                'Mobile' => $this->receiver['mobile'],
                'ProvinceName' => $this->receiver['provinceName'],
                'CityName' => $this->receiver['cityName'],
                'ExpAreaName' => $this->receiver['expAreaName'],
                'Address' => $this->receiver['address'],
            ],
            // 商品信息
            'Commodity' => $this->commodity($this->deliverOrder['commodity']),
            //    'AddService' => [
            //        ['Name' => 'INSURE', 'Value' => '1000'],
            //        ['Name' => 'COD', 'Value' => '1020', 'CustomerID ' => '1234567890']
            //    ],
            // 包裹总重量kg
            'Weight' => $this->deliverOrder['weight'],
            // 包裹数
            'Quantity' => $this->deliverOrder['quantity'],
            // 包裹总体积m3
            // 'Volume' => $this->deliverOrder['volume'],
            // 返回电子面单模板
            'IsReturnPrintTemplate' => 1,
            // 是否通知快递员上门揽件
            'IsNotice' => $this->deliverOrder['isNotice'],
            // 面单备注
            'Remark' => ''
        ]);
        // 组装系统级参数
        $param = [
            'EBusinessID' => $this->options['kdniao']['eBusinessID'],
            'RequestType' => '1007',
            'RequestData' => urlencode($requestData),
            'DataType' => '2',
        ];
        $param['DataSign'] = $this->encrypt($requestData, $this->options['kdniao']['apiKey']);
        // 发送post请求
        $result = $this->curlPost(self::API_URL, $param);
        // 处理返回结果
        $data = helper::jsonDecode($result);
        // 记录日志
        log_record(['name' => '电子面单API', 'provider' => 'kdniao', 'param' => $param, 'result' => $data]);
        // 判断请求状态
        if ($data['Success'] != true || !in_array($data['ResultCode'], [100, 106])) {
            throwError('快递鸟API请求失败：' . ($data['Reason'] ?? '--'));
        }
        return $data;
    }

    /**
     * 电商Sign签名生成
     * @param string $content 内容
     * @param string $apiKey ApiKey
     * @return string
     */
    protected function encrypt(string $content, string $apiKey): string
    {
        return urlencode(base64_encode(md5($content . $apiKey)));
    }

    /**
     * 转义支付参数
     * @param string $value
     * @return int
     */
    private function payType(string $value): int
    {
        $enum = ['SHIPPER' => 1, 'CONSIGNEE' => 2, 'MONTHLY' => 3, 'THIRDPARTY' => 4];
        return $enum[$value];
    }

    /**
     * 转义商品数据
     * @param array $data
     * @return array
     */
    private function commodity(array $data): array
    {
        $commodity = [];
        foreach ($data as $item) {
            $commodity[] = [
                'GoodsName' => $item['goodsName'] . (!empty($item['goodsProps']) ? "【{$item['goodsProps']}】" : ''),
                'Goodsquantity' => $item['goodsquantity'],
                'GoodsWeight' => $item['goodsWeight'],
            ];
        }
        return $commodity;
    }
}